<template>
  <div class="ele-body">
    <a-card class="left" :bordered="false">
      <a-tree :showLine="true" v-if="treeData.length" :tree-data="treeData" :defaultExpandAll="true" v-model:checkedKeys="checkedKeys" :checkable="true" :multiple="true"> </a-tree
    ></a-card>
    <a-card class="right" :bordered="false">
      <a-form :model="qureyInfo" :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="商品类型:">
              <a-select v-model:value="chioseOption" style="width: 120px" :options="Option" @change="serachType"> </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <div class="type_list">
            <div class="type_item" v-for="(item, index) in r_middle" :key="item.id">
              <span>{{ item.rule_name }}:</span>
              <span :class="item.is_active ? 'active' : ''" @click="handleAll(index)">{{ item.allName }}</span>
              <span :class="subItem.is_active ? 'active' : ''" @click="getShuxing(subItem.attr_name, subIndex, index)" v-for="(subItem, subIndex) in item.rule_attr" :key="subItem.id">{{
                subItem.attr_name
              }}</span>
            </div>
          </div>
        </a-row>
        <a-row>
          <a-form-item label="名称" style="margin-right:30px;">
            <a-input v-model:value="sousuos.product_name" />
          </a-form-item>
          <a-form-item label="FUSKU">
            <a-input v-model:value="sousuos.fnsku" />
          </a-form-item>
        </a-row>
        <a-row>
          <a-form-item label="入库时间" :size="12" style="margin-right:30px;">
            <a-space direction="vertical">
              <a-range-picker v-model:value="createTime" show-time @ok="crateTimeChange" />
            </a-space>
          </a-form-item>
          <a-form-item label="更新时间" :size="12" style="margin-right:30px;">
            <a-space direction="vertical">
              <a-range-picker v-model:value="updateTime" show-time @ok="updateTimeChange" />
            </a-space>
          </a-form-item>
          <a-button style="background:#1ab394; margin-left:10px;" shape="round" :size="middle" @click="sousuoLists">
            <span style="color:#fff;" class="iconfont icon-sousuo">搜索</span>
          </a-button>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="table" row-key="id" :datasource="cateLists" :columns="columns" :scroll="{ x: 'max-content' }">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="openAddCate()">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加</span>
            </a-button>
          </a-space>
        </template>
        <template #operation="{ record }">
          <div class="editable-row-operations">
            <span> <a @click="() => purchaseRowIndex(record)">采购</a>&nbsp; </span>
            <span> <a @click="() => editRowIndex(record)">编辑</a>&nbsp; </span>
            <span> <a @click="delRowIndex(record)">删除</a>&nbsp; </span>
          </div>
        </template>
        <template #expandedRowRender="{record}">
          <a-table :columns="innerColums" :data-source="record.attrs" :pagination="false" row-key="id">
            <template #label_data="{ text }">
              <a-tag v-for="item in text" :key="item.id">{{ item.label_name }}</a-tag>
            </template>
            <template #operation="{ record }">
              <div class="editable-row-operations">
                <span> <a @click="() => depotCaigou(record)">采购</a>&nbsp; </span>
                <span> <a @click="() => depotKucun(record)">库存</a>&nbsp; </span>
                <span> <a @click="depotLishi(record)">历史</a>&nbsp; </span>
                <span> <a @click="depotEdit(record)">编辑</a>&nbsp; </span>
                <span> <a @click="depotDelete(record)">删除</a>&nbsp; </span>
              </div>
            </template>
          </a-table>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- sku商品编辑 -->
    <a-modal v-model:visible="huoyuanEditVisible" title="SKU编辑" @ok="handleSkuEditeOk" width="70%">
      <template #footer>
        <a-button key="back" @click="handleSkuEditeOk">确定</a-button>
        <a-button key="submit" type="primary" @click="skuHandleCancel">取消</a-button>
      </template>
      <a-form :model="skuEditInfo" :rules="skuEditInfoRules" ref="skuEditInfoRef" class="skuEdit">
        <a-form-item label="商品规格">
          <span>{{ skuEditInfo.detail_lang }}</span>
        </a-form-item>
        <a-form-item label="图片">
          <a-upload name="file" list-type="picture-card picture" :show-upload-list="false" class="pic" :custom-request="data => onFileUpload(data)">
            <div>
              <img style="height:36px; width:36px;" v-if="imgUrl1 != null" :src="imgUrl1" alt="" />
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="售价" name="price">
          <a-input v-model:value="skuEditInfo.price" style="width: 200px;" placeholder="请输入序列号类型" />
        </a-form-item>
        <!-- SKU -->
        <a-form-item label="成本价" name="cost">
          <a-input style="width: 200px;" v-model:value="skuEditInfo.cost" />
        </a-form-item>
        <!-- 商品编号 -->
        <a-form-item label="商品编号" name="bar_code">
          <a-input v-model:value="skuEditInfo.bar_code" style="width: 200px;" />
        </a-form-item>
        <!-- ASIN -->
        <a-form-item label="重量" name="weight">
          <a-input style="width: 200px;" v-model:value="skuEditInfo.weight" />
        </a-form-item>
        <!-- FNSKU -->
        <a-form-item label="体积" name="volume">
          <a-input style="width: 200px;" v-model:value="skuEditInfo.volume" />
        </a-form-item>
        <a-form-item label="库存预警" name="warning_stock">
          <a-input style="width: 200px;" v-model:value="skuEditInfo.warning_stock" />
        </a-form-item>
        <a-form-item label="低预警数量" name="low_warning">
          <a-input style="width: 200px;" v-model:value="skuEditInfo.low_warning" />
        </a-form-item>

        <a-form-item label="标签">
          <a-select v-model:value="skuEditInfo.label_id" mode="multiple" :options="optionsLabel" @change="handleChange" style="width: 400px;"> </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import qs from 'qs'
export default {
  data() {
    return {
      // sku编辑弹出框的显示和隐藏
      huoyuanEditVisible: false,
      // sku编辑的信息
      skuEditInfo: {},
      // 子表格编辑标签
      optionsLabel: [],
      skuEditInfoRules: {
        bar_code: [
          {
            required: true,
            message: '请输入必填项',
            trigger: 'change'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入必填项',
            trigger: 'change'
          }
        ],
        cost: [
          {
            required: true,
            message: '请输入必填项',
            trigger: 'change'
          }
        ],
        weight: [
          {
            required: true,
            message: '请输入必填项',
            trigger: 'change'
          }
        ],
        volume: [
          {
            required: true,
            message: '请输入必填项',
            trigger: 'change'
          }
        ],
        warning_stock: [
          {
            required: true,
            message: '请输入必填项',
            trigger: 'change'
          }
        ],
        low_warning: [
          {
            required: true,
            message: '请输入必填项',
            trigger: 'change'
          }
        ]
      },
      imgUrl1: '',
      // 左侧树形结构的数据
      treeData: [],
      // 查询数据
      queryInfo: {
        goods_type: 2
      },
      // 商品分类的选择项
      checkedKeys: [],
      // 右边上面的已经选择
      chioseOption: [],
      // 选择列表
      Option: [],
      // 四个搜索
      sousuos: {
        product_name: '',
        fnsku: '',
        create_time_start: '',
        create_time_end: '',
        update_time_start: '',
        update_time_end: ''
      },
      // 右侧中间的数据
      r_middle: [],
      // 表格数据
      cateLists: [],
      // 表格的渲染
      columns: [
        {
          title: '商品名称',
          dataIndex: 'product_name'
        },
        {
          title: '品牌',
          dataIndex: 'pinpaiName'
        },
        {
          title: '库位(数量)',
          dataIndex: 'storage_location'
        },
        {
          title: '库存量',
          dataIndex: 'stock'
        },
        {
          title: '状态',
          dataIndex: 'status'
        },
        {
          title: '路途中/数量',
          dataIndex: 'road_count'
        },
        {
          title: '采购数量',
          dataIndex: 'purchase_count'
        },
        {
          title: '操作',
          slots: { customRender: 'operation' }
        }
      ],
      // 入库时间
      createTime: '',
      // 更新时间
      updateTime: '',
      // 子表的colums  数据
      innerColums: [
        {
          title: 'ID',
          dataIndex: 'id'
        },
        {
          title: '规格信息',
          dataIndex: 'detail_lang'
        },
        {
          title: '警戒数量',
          dataIndex: 'warning_stock'
        },
        {
          title: '低警戒数量',
          dataIndex: 'low_warning'
        },
        {
          title: '库存',
          dataIndex: 'stock'
        },
        {
          title: '库位数量',
          dataIndex: 'storage_location'
        },
        {
          title: '路途中/数量',
          dataIndex: 'road_count'
        },
        {
          title: '采购',
          dataIndex: 'purchase_count'
        },
        {
          title: '标签',
          dataIndex: 'label_data',
          width: 120,
          slots: { customRender: 'label_data' }
        },
        {
          title: '操作',
          slots: { customRender: 'operation' }
        }
      ]
    }
  },
  created() {
    this.getTypeLists()
    this.getSelectDown()
    this.listsInit()
  },
  watch: {
    checkedKeys() {
      this.listChoice()
    },
    queryInfo() {
      this.listsInit()
    }
  },
  methods: {
    // 初始化列表
    async listsInit() {
      const res = await this.$http.get('/depot', { params: this.queryInfo })
      console.log(res.data.data)
      res.data.data.list.forEach(item => {
        if (!(item.product_brand == null)) {
          item.pinpaiName = item.product_brand.brand_name
        }
        if (!(item.product_type == null)) {
          item.pinpaiType = item.product_type.type_name
        }
        if (item.status == 1) {
          item.status = '启用'
        } else {
          item.status = '禁用'
        }
        // 处理子表的数据  detail_lang的数据
        item.attrs.forEach(ele => {
          ele.detail_lang = ele.detail_lang.join()
        })
      })
      this.cateLists = res.data.data.list
    },
    // 获取右侧中间属性的数据
    async getSelectDown() {
      const res = await this.$http.get('/depot/rule_list')
      console.log(res.data.data)
      res.data.data.forEach(item => {
        item.allName = '全部'
        item.is_active = false
        item.rule_attr.forEach(ele => {
          ele.is_active = false
        })
      })
      this.r_middle = res.data.data
      this.queryInfo.attr_name = []
    },
    // 处理属性的点击事件一列属性
    handleAll(index) {
      this.r_middle[index].is_active = !this.r_middle[index].is_active
      let arr = []
      console.log(this.r_middle[index])
      if (this.r_middle[index].is_active == true) {
        this.r_middle[index].rule_attr.forEach(item => {
          item.is_active = true
          arr.push(item.attr_name)
        })
        arr.forEach(item => {
          this.queryInfo.attr_name.push(item)
        })
        this.queryInfo.attr_name = Array.from(new Set(this.queryInfo.attr_name))
      } else {
        this.r_middle[index].rule_attr.forEach(item => {
          item.is_active = false
          arr.push(item.attr_name)
        })
        arr.forEach(item => {
          let flog = this.queryInfo.attr_name.indexOf(item)
          this.queryInfo.attr_name.splice(flog, 1)
          console.log(index)
        })
      }
      this.listsInit()
    },
    // 初始化左侧树形结构
    async getTypeLists() {
      const res = await this.$http.get('/depot/column?is_new=1')
      console.log(res.data.data.list)
      this.treeData = [
        {
          title: '全部商品',
          key: -1,
          children: res.data.data.list
        }
      ]
    },
    // 获取左侧的树形组件的回调
    async listChoice() {
      let obj = {
        goods_type: 2,
        category_id: this.checkedKeys
      }
      const res = await this.$http.post('/depot/type_list', qs.stringify(obj))
      let arr = []
      console.log(res)
      res.data.data.forEach(element => {
        arr.push({ label: element.type_name, value: element.id })
      })
      this.Option = arr
      this.queryInfo.category_id = this.checkedKeys
      this.listsInit()
    },
    // 下拉选择的回调
    async serachType() {
      console.log(this.chioseOption)
      const res = await this.$http.get('/depot/rule_list?type_id=' + this.chioseOption)
      console.log(res.data.data)
      this.r_middle = res.data.data
    },
    // 点击属性单个属性
    async getShuxing(id, childIndex, index) {
      this.r_middle[index].rule_attr[childIndex].is_active = !this.r_middle[index].rule_attr[childIndex].is_active
      if (this.r_middle[index].rule_attr[childIndex].is_active) {
        this.queryInfo.attr_name.push(id)
        this.queryInfo.attr_name = Array.from(new Set(this.queryInfo.attr_name))
      } else {
        let flog = this.queryInfo.attr_name.indexOf(id)
        this.queryInfo.attr_name.splice(flog, 1)
      }
      this.listsInit()
    },
    // 商品搜索
    async sousuoLists() {
      this.queryInfo.product_name = this.sousuos.product_name
      this.queryInfo.fnsku = this.sousuos.fnsku
      this.queryInfo.create_time_start = this.sousuos.create_time_start
      this.queryInfo.create_time_end = this.sousuos.create_time_end
      this.queryInfo.update_time_start = this.sousuos.update_time_start
      this.queryInfo.update_time_end = this.sousuos.update_time_end
      this.listsInit()
      // 清除数据
      this.createTime = ''
      this.updateTime = ''
      this.queryInfo.product_name = ''
      this.queryInfo.fnsku = ''
      this.queryInfo.create_time_start = ''
      this.queryInfo.create_time_end = ''
      this.queryInfo.update_time_start = ''
      this.queryInfo.update_time_end = ''
      this.sousuos = {
        product_name: '',
        fnsku: '',
        create_time_start: '',
        create_time_end: '',
        update_time_start: '',
        update_time_end: ''
      }
      this.$message.success('搜索成功！')
    },
    // 入库时间点击确定的回调
    crateTimeChange() {
      console.log(moment(this.createTime[0]).format('YYYY-MM-DD h:mm:ss'))
      this.sousuos.create_time_start = moment(this.createTime[0]).format('YYYY-MM-DD h:mm:ss')
      this.sousuos.create_time_end = moment(this.createTime[1]).format('YYYY-MM-DD h:mm:ss')
    },
    // 更新时间点击确定的回调
    updateTimeChange() {
      console.log(moment(this.updateTime[0]).format('YYYY-MM-DD h:mm:ss'))
      this.sousuos.update_time_start = moment(this.updateTime[0]).format('YYYY-MM-DD h:mm:ss')
      this.sousuos.update_time_end = moment(this.updateTime[1]).format('YYYY-MM-DD h:mm:ss')
    },
    // 编辑
    editRowIndex(row) {
      console.log(row)
      this.$router.push({ path: '/depot/list/edit', query: { id: row.id } })
    },
    // 删除
    async delRowIndex(row) {
      const { data: res } = await this.$http.delete('/depot/' + row.id)
      if (res.code != 0) this.$message.warning('删除失败')
      this.$message.success('删除成功')
    },
    // 采购
    purchaseRowIndex(row) {
      console.log(row)
    },
    // 添加商品
    openAddCate() {
      this.$router.push('/depot/list/add')
    },
    // 字表格的操作回调
    depotCaigou() {},
    depotKucun() {},
    depotLishi() {},
    async depotEdit(row) {
      const { data: res } = await this.$http.get('/depot/sku/' + row.unique)
      res.data.detail_lang = res.data.detail_lang.join()
      res.data.label_id = res.data.label_id.split(',')
      let arr = []
      res.data.label_id.forEach(item => {
        arr.push(parseInt(item))
      })
      res.data.label_id = arr
      console.log(res.data)
      this.skuEditInfo = res.data
      // 处理图片
      this.imgUrl1 = res.data.pic
      this.getLabelList()
      this.huoyuanEditVisible = true
      console.log(res)
    },
    async depotDelete(row) {
      const { data: res } = await this.$http.delete('/depot/sku/' + row.unique)
      if (res.code != 0) return this.$message.warning('删除失败！')
      this.$message.success('删除成功！')
      this.listsInit()
    },
    // sku编辑的回调
    // 确定
    async handleSkuEditeOk() {
      let obj = {
        unique: this.skuEditInfo.unique,
        pic: this.skuEditInfo.pic.slice(32),
        label_id: this.skuEditInfo.label_id.join(),
        bar_code: this.skuEditInfo.bar_code,
        price: this.skuEditInfo.price,
        cost: this.skuEditInfo.cost,
        weight: this.skuEditInfo.weight,
        volume: this.skuEditInfo.volume,
        warning_stock: this.skuEditInfo.warning_stock,
        low_warning: this.skuEditInfo.low_warning
      }

      const { data: res } = await this.$http.post('/depot/sku/edit', qs.stringify(obj))
      console.log(res)
      if (res.code != 0) return this.$message.warning('编辑失败')
      this.$message.success('编辑成功')
      this.huoyuanEditVisible = false
      this.listsInit()
    },
    // 取消
    skuHandleCancel() {
      this.huoyuanEditVisible = false
    },
    // 子表格编辑获取商品标签
    async getLabelList() {
      const res = await this.$http.get('/product/label')

      let arr = res.data.data.list
      let newArr = []
      arr.forEach(item => {
        newArr.push({ label: item.label_name, value: item.id })
      })
      this.optionsLabel = newArr
      console.log(this.optionsLabel)
    },
    // 上传图片
    async onFileUpload(file) {
      // this.loading[type] = true;
      console.log(file)
      const formData = new FormData()
      formData.append('file', file.file)
      const res = await this.$http.post('/common/upload', formData)
      console.log(res.data.data)
      this.imgUrl1 = process.env.VUE_APP_API_BASE_URL + '/uploads/' + res.data.data
      this.skuEditInfo.pic = process.env.VUE_APP_API_BASE_URL + '/uploads/' + res.data.data
    }
  }
}
</script>

<style lang="less" scoped>
.ele-body {
  display: flex;
  height: 100%;
  .left {
    width: 15%;
    margin-right: 1%;
    height: 100%;
  }
  .right {
    width: 84%;
    height: 100%;
  }
  .type_list {
    width: 100%;
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 10px;
    border-top: 1px solid #47474757;
    border-right: 1px solid #47474757;
    .type_item {
      height: 40px;
      border-bottom: 1px dashed #9b95958a;
      span {
        font-size: 16px;
        line-height: 40px;
        color: #000;
        margin-right: 20px;
        cursor: pointer;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
          'Noto Color Emoji';
      }
      span:first-child {
        color: #00000085;
        width: 80px;
        margin-right: 0px;
        display: inline-block;
        white-space: nowrap;
      }
      span:nth-child(2) {
        font-weight: 600;
        color: #2222228a;
        letter-spacing: 2px;
      }
    }
  }
}
.active {
  color: red !important;
  font-weight: 600 !important;
}
.ant-modal-body {
  .skuEdit {
    /deep/ .ant-form-item-control {
      width: 40% !important;
    }
    /deep/ .ant-upload.ant-upload-select-picture-card {
      height: 40px !important;
      width: 40px !important;
    }
    /deep/ .ant-form-horizontal .ant-form-item-label {
      width: 100px !important;
    }

    /deep/ .ant-form-item {
      .ant-form-item-label {
        width: 100px !important;
      }
    }
  }
}
</style>
